package com.mfz.users

import com.mfz.common.persistence.AbstractFactory
import com.mfz.common.persistence.AbstractPersistence
import com.mfz.common.units.ID
import com.mfz.users.definition.COMPANY_ID


private const val SQL_SUB_DEPS = "WITH RECURSIVE deptree(id) AS (select id from department d where id = %d union select d.id from department d, deptree dt where dt.id = d.parent_id)select id from deptree"

private const val SQL_LINK_USER = "id in (select department_id from l_users_department where user_id = %d)"

/**
 *
 * create by 2020/1/23.
 * @author zhengyimin
 */
class Department private constructor() : AbstractPersistence(Companion), com.mfz.common.definition.organization.Department {
	private lateinit var _ownerCompany: Company
	private lateinit var _departments: List<Department>
	private lateinit var _users: List<User>


	override val departments: Collection<Department>
		get() {
			if (!this::_departments.isInitialized) {
				_departments = Department.getPersistences("id in (${String.format(SQL_SUB_DEPS, id)})")
			}

			return _departments
		}

	override val ownerCompany: Company
		get() {
			if (!this::_ownerCompany.isInitialized) {
				_ownerCompany = Company.get(ID, get(COMPANY_ID, -1))!!
			}

			return _ownerCompany
		}
	override val isAvailable: Boolean
		get() = flag.notDelete && ownerCompany.isAvailable

	override val users: Collection<User>
		get() {
			if (!this::_users.isInitialized) {
				_users = User.loadUsersInDepartment(this.id)
			}

			return _users
		}

	companion object : AbstractFactory<Department>("department") {
		init {
			useBuffer = true
		}

		override fun createNewObject(): Department {
			return Department()
		}

		fun loadCompanyDepartments(companyId: Int): List<Department> {
			return getPersistences("company_id = $companyId")
		}

		fun loadInvolveUsers(userId: Int): List<Department> {
			return getPersistences(String.format(SQL_LINK_USER, userId))
		}
	}
}
